package org.flh.book.shop.interceptor;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.flh.book.shop.common.response.RestResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 描述：全局异常拦截器
 *
 * @date 2021/1/22 15:59
 * @author 花好月圆
 */
@ControllerAdvice
public class GlobalExceptionInterceptor {

    @ExceptionHandler(value = Exception.class)
    public void globalExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e)
        throws IOException {
        String requestURI = request.getRequestURI();
        String message = "操作异常----->请求地址：" + requestURI + "\n" +
            " \t\t请求参数：" + JSON.toJSONString(request.getParameterMap()) + "";
        outLogError(requestURI, "GLOBAL_EXCEPTION", "EXCEPTION", message, e);
        setExceptionMessage(response, RestResponse.fail("系统异常，请联系管理员！"));
    }

    /**
     * 先将错误打印在控制台
     */
    private void outLogError(String requestURI, String module, String action, String message,Throwable throwable) {
        System.out.println("请求地址："+requestURI);
        System.out.println("所属模块："+module);
        System.out.println("动作："+action);
        System.out.println("详细信息："+message);
        System.out.print("错误堆栈信息：");
        throwable.printStackTrace();
    }

    private void setExceptionMessage(HttpServletResponse res, Object message) throws IOException {
        res.setStatus(200);
        res.setCharacterEncoding("utf8");
        res.setHeader("Content-type", "text/html;charset=UTF-8");
        res.resetBuffer();
        res.getWriter().write(message instanceof String ?
            String.valueOf(message) : JSON.toJSONString(message));
    }

}
